package top.codedance.iotp.server.net.handle.subhandle.controller.http.async;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.TcpServer;
import top.codedance.iotp.server.net.handle.WsChannelHandler;
import top.codedance.iotp.server.net.handle.exception.ChannelNotFoundException;
import top.codedance.iotp.server.net.handle.exception.DeviceOfflineException;
import top.codedance.iotp.server.net.handle.exception.NotAccessException;
import top.codedance.iotp.server.net.handle.exception.ParamNotEmptyException;
import top.codedance.iotp.server.net.handle.subhandle.controller.AdapterWsController;
import top.codedance.iotp.server.net.session.Session;

import java.nio.charset.StandardCharsets;

public class MqttExecController extends AdapterWsController {

    @Override
    public void doSubHandler(WsChannelHandler wsChannelHandle, String clientId, JSONObject jsonObject) {
        try {
            if (!userVerification()) {
                throw new NotAccessException();
            }
            Session session = TcpServer.sessionManager.getSessionByDeviceId(jsonObject.getString("deviceId"));
            if (session == null) {
                throw new DeviceOfflineException();
            }
            if (session.getChannel() == null) {
                throw new ChannelNotFoundException();
            }
            Integer instance = jsonObject.getInteger("instance");
            if (instance == null) {
                throw new ParamNotEmptyException();
            }
            JSONObject outputJo = new JSONObject();
            outputJo.put("clientId", clientId);
            JSONObject result = cleanServerParamsAndJoin(jsonObject, outputJo);
            CommonEntity commonEntity2 = new CommonEntity(ServerApplication.getDataVersion());
            commonEntity2.setCommand(Command.ASYNC_MQTT_COMMAND);
            commonEntity2.setBody(result.toJSONString().getBytes(StandardCharsets.UTF_8));
            session.getChannel().writeAndFlush(commonEntity2.build());
        } catch (DeviceOfflineException | ChannelNotFoundException ex){
            wsChannelHandle.wsSend(clientId, response500("Device offline"));
        } catch (ParamNotEmptyException e){
            wsChannelHandle.wsSend(clientId, response500("'instance' parameter is not empty."));
        } catch (NotAccessException e){
            wsChannelHandle.wsSend(clientId, response403( "No access"));
        }
    }
}
